"""
数据库CRUD操作
"""
from sqlalchemy.orm import Session
from app.models.database import Database
from typing import Optional, List

def get_database_by_id(db: Session, database_id: int) -> Optional[Database]:
    """根据ID获取数据库"""
    return db.query(Database).filter(Database.id == database_id).first()

def get_databases(db: Session, skip: int = 0, limit: int = 100) -> List[Database]:
    """获取数据库列表"""
    return db.query(Database).filter(Database.is_deleted == False).offset(skip).limit(limit).all()

def get_databases_by_status(db: Session, status: str) -> List[Database]:
    """根据状态获取数据库列表"""
    return db.query(Database).filter(Database.status == status, Database.is_deleted == False).all()

def create_database(db: Session, database_data: dict) -> Database:
    """创建数据库"""
    db_database = Database(**database_data)
    db.add(db_database)
    db.commit()
    db.refresh(db_database)
    return db_database

def update_database(db: Session, database_id: int, database_data: dict) -> Optional[Database]:
    """更新数据库信息"""
    db_database = get_database_by_id(db, database_id)
    if db_database:
        for key, value in database_data.items():
            setattr(db_database, key, value)
        db.commit()
        db.refresh(db_database)
    return db_database

def delete_database(db: Session, database_id: int) -> bool:
    """删除数据库(软删除)"""
    db_database = get_database_by_id(db, database_id)
    if db_database:
        db_database.is_deleted = True
        db.commit()
        return True
    return False